package com.istock.monitor.agent.spring;

import org.apache.commons.lang3.reflect.MethodUtils;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;

import com.istock.monitor.agent.config.PropertiesLoader;

public abstract class SpringInjector {

	public static void registerBeanPostProcessor(ConfigurableListableBeanFactory beanFactory){
		System.out.println("==========SpringInjector==========");
		try{
//			ClassLoader classLoader = beanFactory.getBeanClassLoader();
			ClassLoader classLoader = (ClassLoader)MethodUtils.invokeMethod(beanFactory,"getBeanClassLoader",new Object[]{});
			Class.forName("org.springframework.beans.factory.support.BeanDefinitionRegistry",false,classLoader);
//			Class.forName("org.springframework.beans.factory.config.ConfigurableListableBeanFactory",false,classLoader);
			
			System.out.println("==========SpringInjector.addBeanDefinition==========");
			
//			Class rootBeanDefinitionClass = classLoader.loadClass("org.springframework.beans.factory.support.RootBeanDefinition");
			Class targetBeanClass = classLoader.loadClass("com.istock.monitor.agent.spring.DataSourceBeanPostProcessor");
			RootBeanDefinition obj = new RootBeanDefinition(targetBeanClass);
			MethodUtils.invokeMethod(beanFactory, "registerBeanDefinition", new Object[]{"dataSourceAgent",obj});
			
			Class aopFactoryBeanClass = classLoader.loadClass("com.istock.monitor.agent.spring.AutoAOPBeanFactoryPostProcessor");
			RootBeanDefinition aopFactoryDef = new RootBeanDefinition(aopFactoryBeanClass);
			aopFactoryDef.getPropertyValues().add("expression", PropertiesLoader.getInstance().get("expression"));
			MethodUtils.invokeMethod(beanFactory, "registerBeanDefinition", new Object[]{"CMP-Factory-Register",aopFactoryDef});
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
